/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lambkit.module.upms.server;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.lambkit.common.LambkitResult;
import com.lambkit.plugin.auth.AuthManager;
import com.lambkit.module.upms.UpmsManager;
import com.lambkit.module.upms.common.LoginService;
import com.lambkit.module.upms.common.UpmsResult;
import com.lambkit.module.upms.common.UpmsResultConstant;

public class UpmsEmbeddedLoginService implements LoginService {

	public void captcha(Controller c) {
    	c.renderCaptcha();
	}
	
    public void login(Controller c) {
    	if (c.getRequest().getMethod().equals("GET")) {
    		Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            String serverSessionId = session.getId().toString();
            // 判断是否已登录，如果已登录，则回跳
            String code = UpmsManager.me().getCache().getSession(serverSessionId);
            String username = (String) subject.getPrincipal();
            // code校验值
            if (StringUtils.isNotBlank(code) && StrKit.notBlank(username) && !username.equals("null")) {
                // 回跳
                String backurl = c.getRequest().getParameter("backurl");
                //String username = (String) subject.getPrincipal();
                if (StringUtils.isBlank(backurl)) {
                    backurl = "/";
                    backurl = subject.hasRole("admin") ? "/manage" : "";
                    backurl = subject.hasRole("super") ? "/manage" : "";
                } else {
                    if (backurl.contains("?")) {
                        backurl += "&upms_code=" + code + "&upms_username=" + username;
                    } else {
                        backurl += "?upms_code=" + code + "&upms_username=" + username;
                    }
                }
                System.out.println("认证中心帐号通过，带code回跳：{}" + backurl);
                if(backurl.startsWith("/")) backurl = backurl.substring(1);
                c.redirect(backurl);
            } else {
            	c.keepPara();
            	//renderJsp("login.jsp");
            	c.renderTemplate("login.html");
            }
    	} else {
    		c.renderJson(AuthManager.me().getService().login(c));
    	}
    }
    
    public void logout(Controller c) {
    	LambkitResult result = AuthManager.me().getService().logout(c.getRequest());
        String redirectUrl = result.getData().toString();
        if (null == redirectUrl) {
            redirectUrl = "/";
        }
        if(redirectUrl.startsWith("/")) redirectUrl = redirectUrl.substring(1);
        c.redirect(redirectUrl);
    }
    
    public void ajaxLogout(Controller c) {
    	AuthManager.me().getService().logout(c.getRequest());
    	c.renderJson(new UpmsResult(UpmsResultConstant.SUCCESS, "logout"));
    }
    
}
